import {
  Controller,
  Get,
  Post,
  Body,
  HttpException,
  HttpStatus,
  Req,
  UseGuards
} from '@nestjs/common'
import { AuthService } from './auth.service'
import { UserService } from 'src/user/user.service'
import { MenuService } from './menu/menu.service'
import { ChangePasswordDto, LoginDto } from './dto/auth.dto'
import { HttpExceptionEnum } from 'types/http-exception'
import { Public, ResponseMsg } from 'src/common/custom.decorator'
import { EasyRequest } from 'types/global'
import { LoggerGuard } from 'src/logger/logger.guard'
@Controller('auth')
export class AuthController {
  constructor(
    private readonly authService: AuthService,
    private readonly userService: UserService,
    private readonly menuService: MenuService
  ) {}

  @Public()
  @ResponseMsg('登录')
  @Post('login')
  @UseGuards(LoggerGuard)
  async login(@Body() loginDto: LoginDto) {
    const user = await this.userService.validateUser(
      loginDto.name,
      loginDto.password
    )

    if (!user) {
      throw new HttpException(
        HttpExceptionEnum.USER_NOT_EXIST,
        HttpStatus.BAD_REQUEST
      )
    }
    return this.authService.login(user, loginDto.expiresInDays)
  }

  @Post('logout')
  @ResponseMsg('登出')
  logout() {
    // 实现登出逻辑，这里简单返回成功消息
    return { message: 'Logged out successfully' }
  }

  @Get('userInfo')
  @ResponseMsg('获取用户信息')
  async userInfo(@Req() req: EasyRequest) {
    const userInfo = await this.userService.findOne(req.user.userId)

    const auth = await this.menuService.findMenuTreeByRoleId(userInfo.roleId)
    return {
      userInfo,
      auth
    }
  }

  @Post('changePassword')
  @ResponseMsg('修改密码')
  @UseGuards(LoggerGuard)
  changePassword(
    @Req() req: EasyRequest,
    @Body() changePasswordDto: ChangePasswordDto
  ) {
    return this.userService.changePassword(req.user.userId, changePasswordDto)
  }
}
